package com.chenxinzhimusic

import MusicPlayerScreen
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import androidx.media3.common.C
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage
import com.chenxinzhimusic.data.getDataContentValue
import com.chenxinzhimusic.data.musicSettingKey
import com.chenxinzhimusic.di.appModule
import com.chenxinzhimusic.entity.MusicSetting
import com.chenxinzhimusic.entity.updateMusicPos
import com.chenxinzhimusic.service.MusicService
import com.chenxinzhimusic.service.MusicService.Companion.controller
import com.chenxinzhimusic.ui.page.MusicSearchScreen
import com.chenxinzhimusic.ui.page.PlayList
import com.chenxinzhimusic.ui.page.RequestNotificationPermissionWithConfirm
import com.chenxinzhimusic.ui.theme.MusicTheme
import com.chenxinzhimusic.viewmodel.MusicViewModel
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import dev.chrisbanes.haze.HazeProgressive
import dev.chrisbanes.haze.HazeState
import dev.chrisbanes.haze.hazeEffect
import dev.chrisbanes.haze.hazeSource
import dev.chrisbanes.haze.rememberHazeState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.compose.koinViewModel
import org.koin.core.context.GlobalContext
import org.koin.core.context.GlobalContext.startKoin
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.DurationUnit

var sharedFlow: MutableSharedFlow<Unit> = MutableSharedFlow(0, 1)
var refreshFlow: MutableSharedFlow<Unit> = MutableSharedFlow(1, 1)


class MainActivity : ComponentActivity() {
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        if (intent.action == null) {
            sharedFlow.tryEmit(Unit)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        // 确保启动背景在onCreate之前已设置
        super.onCreate(savedInstanceState)
        val context = this@MainActivity
        if (GlobalContext.getOrNull() == null) {
            startKoin {
                androidContext(context)
                modules(appModule)
            }

        }
        // 确保服务已启动
        val intent = Intent(context, MusicService::class.java)
        ContextCompat.startForegroundService(context, intent)
        // 创建 SessionToken 并构建 Controller
        val token = SessionToken(context, ComponentName(context, MusicService::class.java))
        val controllerFuture: ListenableFuture<MediaController> =
            MediaController.Builder(this, token).buildAsync()
        controllerFuture.addListener(
            {
                controller = controllerFuture.get()
            },
            MoreExecutors.directExecutor()
        )
        // 在设置内容前，确保系统UI配置正确
        enableEdgeToEdge(
            statusBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT),
            navigationBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT)
        )

        // 设置内容视图
        setContent {
            MusicTheme {
                MusicAppNavHost()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        controller?.release()
    }
}

// Navigation.kt
@SuppressLint("ConfigurationScreenWidthHeight")
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@OptIn(UnstableApi::class)
@Composable
fun MusicAppNavHost(musicViewModel: MusicViewModel = koinViewModel()) {
    val hazeState = rememberHazeState()
    val navController = rememberNavController()
    var showPlayer by rememberSaveable { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        launch(Dispatchers.IO) {
            sharedFlow.collect {
                showPlayer = true
            }
        }

    }

    val current = LocalContext.current
    //首次启动
    var show by remember { mutableStateOf(false) }
    RequestNotificationPermissionWithConfirm(show) {
        show = false
    }
    val lifecycleOwner = LocalLifecycleOwner.current

    LaunchedEffect(Unit) {
        show = !NotificationManagerCompat.from(current)
            .areNotificationsEnabled()
        current.getDataContentValue<MusicSetting>(musicSettingKey)?.let {
            musicViewModel.musicId = it.currentMusic.musicId
            //设置为当前播放音乐
            while (controller == null) {
                delay(100)
            }
            controller?.repeatMode = it.repeatMode
            controller?.shuffleModeEnabled = it.shuffle
            MusicService.playList(it.currentMusic, it.playList.musicList, it.isPlay)

        }
    }
    // 监听进度
    LaunchedEffect(Unit) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
            while (true) {
                musicViewModel.isPlaying = controller?.isPlaying == true
                musicViewModel.cover =
                    controller?.currentMediaItem?.mediaMetadata?.artworkUri?.toString()
                        ?: ""
                delay(200)
            }
        }

    }


    LaunchedEffect(Unit) {
        while (true) {
            current.updateMusicPos(
                controller?.currentPosition?.takeIf { it != C.TIME_UNSET && it > 0 }?.milliseconds?.toInt(
                    DurationUnit.SECONDS
                )
                    ?: 0,
                controller?.isPlaying == true,
                controller?.currentMediaItem?.mediaId ?: "",
                controller?.repeatMode,
                controller?.shuffleModeEnabled
            )
            delay(5000)
        }
    }
    LaunchedEffect(musicViewModel.isPlaying) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
            if (musicViewModel.isPlaying) {
                musicViewModel.rotation.animateTo(
                    musicViewModel.rotation.value + 360f,
                    infiniteRepeatable(tween(10000, easing = LinearEasing))
                )
            }
        }

    }
    Scaffold(
        bottomBar = {
            BottomNavigationBar(navController, hazeState)
        },
        floatingActionButton = {
            Box(
                modifier = Modifier
                    .offset(y = 80.dp)
                    .size(if (LocalConfiguration.current.screenWidthDp < 360) 70.dp else 84.dp)
                    .clip(CircleShape)
                    .clickable {
                        showPlayer = true
                    }
                    .background(Color.White.copy(alpha = 0.15f)),
                contentAlignment = Alignment.Center
            ) {
                if (musicViewModel.cover.isNotBlank()) {
                    AsyncImage(
                        model = musicViewModel.cover,
                        contentDescription = "封面图",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .size(80.dp)
                            .clip(CircleShape)
                            .graphicsLayer(
                                rotationZ = musicViewModel.rotation.value
                            )
                    )
                }
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.4f))
                )
                Text(
                    if (musicViewModel.isPlaying) "正在播放" else "未播放",
                    color = Color.White.copy(alpha = 0.9f)
                )
            }

        },
        floatingActionButtonPosition = FabPosition.Center,
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize()) {
            AsyncImage(
                model = R.drawable.bg,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .hazeSource(hazeState)
                    .fillMaxSize()
                // 添加模糊
            )
            // 半透明遮罩增强前景可读性
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.6f))
            )

            NavHost(
                navController = navController,
                startDestination = "home",
                modifier = Modifier.padding(paddingValues)
            ) {
                composable("home") {
                    MusicSearchScreen(sharedFlow = sharedFlow)
                }
                composable("list") {
                    PlayList(sharedFlow)
                }
            }
        }

    }
    AnimatedVisibility(
        showPlayer,
        enter =
            slideInVertically(
                initialOffsetY = { it }, // 从底部进入
                animationSpec = tween(500)
            ),
        exit =
            slideOutVertically(
                targetOffsetY = { it }, // 向上退出
                animationSpec = tween(500)
            ),
    ) {
        MusicPlayerScreen(musicViewModel) {
            showPlayer = false
        }
    }


}

// BottomBar.kt
@SuppressLint("ConfigurationScreenWidthHeight")
@Composable
fun BottomNavigationBar(navController: NavHostController, hazeState: HazeState) {
    val items = listOf("发现" to "home", "播放列表" to "list")
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    Box(
        modifier = Modifier
            .height(if (LocalConfiguration.current.screenWidthDp < 360) 70.dp else 80.dp)
            .fillMaxWidth()
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
            // 添加模糊
        ) {
            Box(
                modifier = Modifier
                    .hazeEffect(hazeState) {
                        progressive =
                            HazeProgressive.verticalGradient(startIntensity = 2f, endIntensity = 1f)
                    }
                    .fillMaxSize()) {

            }
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.6f))
            ) {

            }
        }
        NavigationBar(
            containerColor = Color.Transparent,
            modifier = Modifier.padding(horizontal = if (LocalConfiguration.current.screenWidthDp < 360) 4.dp else 8.dp),
            tonalElevation = 0.dp
        ) {
            items.forEach { screen ->
                NavigationBarItem(
                    icon = { Icon(Icons.Default.MusicNote, contentDescription = null) },
                    label = { Text(screen.first) },
                    selected = navBackStackEntry?.destination?.route == screen.second,
                    colors = NavigationBarItemDefaults.colors(
                        unselectedIconColor = Color.Gray,
                        unselectedTextColor = Color.Gray,
                        selectedIconColor = Color.White,
                        selectedTextColor = Color.White, indicatorColor = Color.Transparent
                    ),
                    onClick = {
                        navController.navigate(screen.second) {
                            launchSingleTop = true
                            restoreState = true
                            popUpTo(navController.graph.findStartDestination().id) {
                                saveState = true
                            }
                        }
                    },
                    interactionSource = remember
                    {
                        object : MutableInteractionSource {
                            override suspend fun emit(interaction: Interaction) {

                            }

                            override fun tryEmit(interaction: Interaction): Boolean {
                                return true
                            }

                            override val interactions: Flow<Interaction>
                                get() = MutableSharedFlow(
                                )

                        }
                    })
            }
        }
    }
}


